package com.android.webserver.fwapi;


import android.content.Context;
import android.text.TextUtils;

public abstract class HTMLPage extends WebPage
{

	private String			response_content;
	static private String	CONTENT_TYPE	= "text/html";

	public HTMLPage(Context context, Request request)
	{
		super(context, request);
		isHTML = true;
		response_content = "";
	}
	
	@Override
	protected boolean create(Object... objects)
	{
		return true;
	}

	@Override
	protected void finish()
	{
		response_contentByteArray = response_content.getBytes();
		header("Content-Length: " + response_contentByteArray.length);
		header("Content-Type: " + CONTENT_TYPE);
	}

	/**
	 * Append content at the end of the HTML page content. DO NOT USE this function if you want to append dynamic content like request parameters ! USE appendHTMLContent(String content, String[] contentArgs) instead. 
	 * @param content Content to append to the HTML page content.
	 */
	protected void appendStaticHTMLContent(String content)
	{
		response_content += content;
	}
	
	/**
	 * Append content at the end of the HTML page content. For best security, to append
	 * dynamic content, include $ in content, which will be replaced by the values
	 * from contentArgs. To append a "$", use its HTML encoded value instead : %24.
	 * For example : appendHTMLContent("&lt;p&gt;$&lt;/p&gt;", getParameter("name"));
	 * @param content			Content to append to the HTML page content.
	 * @param contentArgs	You may include ? in content, which will be replaced by the values from contentArgs, in order that they appear in the selection. The values will be bound as Strings.
	 */
	protected void appendHTMLContent(String content, String[] contentArgs)
	{
		int pos = 0;
		int contentArgsPos = 0;
		pos = content.indexOf('$', pos);
		String escaped = "";
		
		while (pos > 0)
		{
				escaped = TextUtils.htmlEncode(contentArgs[contentArgsPos++]);
				content = content.substring(0, pos)
				+ escaped
				+ content.substring(pos + 1);
			pos = pos + escaped.length();
			pos = content.indexOf('$', pos);
		}
		
		response_content += content;
	}
}
